<template>
  <div>
    <div>
      <el-form :inline="true" :model="param">
        <el-col :span="7">
          <el-form-item label="商品名称">
            <el-input @clear="findGoods" v-model="param.name" placeholder="筛选名称" clearable
                      prefix-icon="el-icon-search"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item></el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button type="primary" @click="findGoods">查询</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button type="success" @click="addGoods">新增</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <div style="margin-bottom: 10px ;">

      <el-table ref="userTable" :data="tableData" :stripe="true" :border="true"
                style="width: 100%">
        <el-table-column prop="name" label="商品名" width="100"></el-table-column>
        <el-table-column prop="createName" label="添加人" width="70"></el-table-column>
        <el-table-column prop="createTime" label="添加时间"></el-table-column>
        <el-table-column prop="num" label="库存/件" width="110"></el-table-column>
        <el-table-column prop="bid" label="进价/元"></el-table-column>
        <el-table-column prop="price" label="售价/元"></el-table-column>
        <el-table-column prop="status" label="商品状态" width="100" align="center">
          <template v-slot="{row}">
            <el-tag type="danger" v-if="row.status === 2" size="small">下架</el-tag>
            <el-tag v-else size="small">上架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template v-slot="scope">
            <el-button @click="down(scope.row)" type="text" size="small">下架</el-button>
            <el-button @click="up(scope.row)" type="text" size="small">上架</el-button>
            <el-button @click="doDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background :page-sizes="[8, 16, 30]" @current-change="pageChange($event)"
                     :page-size=this.param.size @size-change="sizeChange($event)"
                     layout="total,prev,pager,next,sizes" :total="total" small>
      </el-pagination>
      <!--新增-->
      <el-dialog title="新增商品" :visible.sync="isAdding" width="30%" :close-on-click-modal="false" center>
        <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px">
          <el-form-item label="商品名" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="库存" prop="num">
            <el-input v-model="addForm.num">
              <template slot="append">件</template>
            </el-input>
          </el-form-item>
          <el-form-item label="进价" prop="bid">
            <el-input v-model="addForm.bid">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="售价" prop="price">
            <el-input v-model="addForm.price">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addForm')">重置</el-button>
        <el-button type="primary" @click="add('addForm')">确认</el-button></span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import check from "@/utils/check"

export default {
  name: "Commodity",
  data() {
    const checkPrice = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请次输入价格'));
      } else if (value < this.addForm.bid) {
        callback(new Error('售价应大于进价'));
      } else {
        callback();
      }
    };
    return {
      userInfo: [],
      tableData: [],
      total: 0,
      isAdding: false,
      param: {
        name: '',
        page: 1,
        size: 8,
      },
      addForm: {
        name: '',
        num: '',
        price: '',
        bid: '',
        createName: '',
      },
      goods: {},
      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
        num: [
          {required: true, validator: check.checkNum, trigger: 'blur'},
          {min: 1, max: 9999, message: '长度在 1 到 9999 个字符', trigger: 'blur'}
        ],
        bid: [
          {required: true, validator: check.checkNum, trigger: 'blur'},
        ],
        price: [
          {required: true, validator: check.checkNum, trigger: 'blur'},
          {required: true, validator: checkPrice, trigger: 'blur'},
        ]
      },
    }
  },
  mounted() {
    this.findGoods();
    this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"))
  },
  methods: {
    findGoods() {
      this.$axios.get('/api/com/findCom', {params: this.param}).then(res => {
        if( res.data.status === 1){
          this.tableData = res.data.data.list
          this.total = res.data.data.total;
        }else {
          this.$notify({
            title: '提示',
            message: '查询失败',
            type: 'error'
          });
        }
      }).catch(e => console.log(e));
    },
    addGoods() {
      this.isAdding = true
    },
    add(addForm) {
      this.$refs[addForm].validate((valid) => {
        if (valid) {
          this.addForm.createName = this.userInfo.name
          this.$axios.post('/api/com/addGoods', this.addForm).then(res => {
            if (res.data.status === 1) {
              this.$notify({
                title: '提示',
                message: '添加成功!',
                type: 'success'
              })
              this.isAdding = false;
              this.findGoods()
            } else {
              this.$notify({
                title: '提示',
                message: res.data.message,
                type: 'error'
              })
            }
          })
        }else {
          return false
        }
      })
    },
    down(row) {
      console.log(row)
      this.goods.id = row.id
      this.goods.status = 2
      this.upApi()
    },
    doDelete(row) {
      this.$confirm('将要删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row)
        if (row.status !== 1) {
          let ids = row.id
          return this.$axios.delete(`/api/com/delGoods?ids=${ids}`).then(res => {  //物理删除
            if (res.data.status === 1) {  //删除成功
              this.$notify({
                title: '提示',
                message: '删除成功',
                type: 'success'
              });
              this.findGoods();
            } else {
              this.$notify({
                title: '提示',
                message: res.data.message,
                type: 'error'
              });
            }
          }).catch(e => e);
        } else {
          this.$notify({
            title: '提示',
            message: '该商品上架中,暂时无法删除',
            type: 'error'
          });
        }
      })
    },
    up(row) {
      this.goods.id = row.id
      this.goods.status = 1
      this.upApi()
    },
    upApi() {
      this.$axios.post('/api/com/upGoods', this.goods).then(res => {
        if (res.data.status === 1) {
          this.$notify({
            title: '提示',
            message: '操作成功',
            type: 'success'
          });
          this.findGoods()
        } else {
          this.$notify({
            title: '提示',
            message: res.data.message,
            type: 'error'
          });
        }
      })
    },


    resetForm(addForm) {
      this.$nextTick(() => {
        this.$refs[addForm].resetFields();
      })
    },
    pageChange(page) {
      this.param.page = page;
      this.findGoods()
    },
    sizeChange(size) {
      this.param.size = size;
      this.findGoods()
    },
  }

}
</script>

<style scoped>

</style>
